<template>
    <div class="fast_date_picker">
        <div class="mask" @click="cancelPicker" v-if="pickerVisible"></div>
        <div class="btns">
            <slot name="before"></slot>
            <p class="btn"
                @click="changeFastDate(i.value)"
                :class="{active: actFast == i.value}"
                v-for="i in showFastList" :key="i.value">
                {{i.label}}
            </p>
            <p class="btn"
                v-if="costom"
                @click="changeFastDate('-')"
                :class="{active: actFast == '-'}">
                <template v-if="actFast == '-'"> {{searchTime[0]}}~{{searchTime[1]}} </template>
                <template v-else> 自定义 </template>
            </p>
            <slot name="after"></slot>
        </div>
        <div class="picker" v-if="pickerVisible">
            <div class="date_range flex-between flex-v-center">
                <div class="start_date" :style="{borderColor: actPicker == 'start' ? '@mainColor' : '#fff'}" @click="setDateToPick('start')">{{startDate}}</div>
                <span>至</span>
                <div class="end_date" :style="{borderColor: actPicker == 'end' ? '@mainColor' : '#fff'}" @click="setDateToPick('end')">{{endDate}}</div>
            </div>
            <picker-view :value="pickerValue" class="picker_view" @change="pickerChange">
                <picker-view-column>
                    <view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
                </picker-view-column>
                <picker-view-column>
                    <view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
                </picker-view-column>
                <picker-view-column>
                    <view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
                </picker-view-column>
            </picker-view>
            <div class="confirm_btn" @click="comfirmDate">确定</div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return{
            searchTime: [],

            lastActFast: '', //上一次选中的快捷时间，用于取消自定义事件选择的时候用的
            actFast: '', //当前选中的快捷时间按钮

            years: [],
            months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
            days: [],

            // 自定义事件选择的相关数据
            pickerVisible: false,
            actPicker: 'start',
            pickerValue: [0,0,0],
            startDate: '',
            endDate: ''
        }
    },
    computed: {
        showFastList() {
            let fastList = [
                {label: '今日', value: '00'},
                {label: '昨日', value: '01'},
                {label: '本周', value: '02'},
                {label: '上周', value: '03'},
                {label: '本月', value: '04'},
                {label: '上月', value: '05'},
                {label: '近7天', value: '06'},
                {label: '近30天', value: '07'},
                {label: '近90天', value: '08'},
                {label: '近180天', value: '09'},
            ]
            return fastList.filter(i => this.types.indexOf(i.value) > -1)
        }
    },
    props: {
        value: {
            type: Array,
            default: () => []
        },
        types: {
            type: String,
            default: '00,01,02,03,04,05,06,07,08'
        },
        costom: {
            type: Boolean,
            default: true
        }
    },
    watch: {
        value: {
            handler(val) {
                this.searchTime = val
                this.setDefaultActFast()
            },
            deep: true
        }
    },
    mounted() {
        this.searchTime = this.value
        this.setDefaultActFast()
        let nowYear = new Date().getFullYear()
        for(let i = 0; i < 6 ; i++) {
            this.years.push(nowYear - i)
        }
        this.setDays(nowYear, new Date().getMonth() + 1)
    },
    methods: {
        // 切换 今日 明日 等快捷时间按钮
        changeFastDate(value, noUpdate) {
            this.lastActFast = this.actFast
            this.actFast = value
            if(value == '-') {
                this.startDate = this.searchTime[0] || new Date().format('yyyy-MM-dd')
                this.endDate = this.searchTime[1] || new Date().format('yyyy-MM-dd')
                this.actPicker = 'start'
                this.setDays(new Date().getFullYear(), new Date().getMonth() + 1)
                this.setPickerValue(this.startDate)
                this.pickerVisible = true
                this.searchTime = [this.startDate, this.endDate]
            } else {
                this.pickerVisible = false
                let searchTime = this.getFormatDate(value)
                this.searchTime = searchTime
                console.log(searchTime);
                if(!noUpdate) {
                    this.updateFatherComp()
                }
            }
        },

        // 切换自定义里的开始时间和结束时间
        setDateToPick(type) {
            if(type == 'start') {
                this.actPicker = 'start'
                this.setPickerValue(this.startDate)
            } else {
                this.actPicker = 'end'
                this.setPickerValue(this.endDate)
            }
        },
        // 选择自定义日期的change事件
        pickerChange(e) {
            let year = this.years[e.detail.value[0]]
            let month = this.months[e.detail.value[1]]
            this.setDays(year, +month)
            this.pickerValue = e.detail.value
            if(this.actPicker == 'start') {
                this.startDate = `${year}-${month}-${this.days[e.detail.value[2]]}`
            } else if(this.actPicker == 'end') {
                this.endDate = `${year}-${month}-${this.days[e.detail.value[2]]}`
            }
        },

        // 根据日期设置picker的value，定位到对应的日期
        setPickerValue(date) {
            let year = date.slice(0, 4)
            let month = date.slice(5, 7)
            let day = date.slice(8, 10)
            this.pickerValue = [this.years.findIndex(i => i == year) , month - 1, day - 1]
        },
        // 确定选择日期
        comfirmDate() {
            let searchTime = [this.startDate, this.endDate]
            searchTime.sort((a, b) => new Date(a) - new Date(b))
            this.searchTime = searchTime
            this.pickerVisible = false
            this.updateFatherComp()
        },
        // 向父级组件出发change事件
        updateFatherComp() {
            this.$emit('input', this.searchTime)
            this.$emit('change', this.searchTime)
        },

        // 点击空白遮罩取消自定义日期，返回上次的快捷选择，并且不执行change事件
        cancelPicker() {
            this.changeFastDate(this.lastActFast || this.showFastList[0].value, true)
            this.pickerVisible = false
        },
        // 根据不同的年月设置当月天数
        setDays(year, month) {
            let daysNum = new Date(year, month, 0).getDate();
            let days = []
            for(let i = 1; i < daysNum ; i++) {
                let day = i
                if(day < 10) {
                    day = '0' + day
                }
                days.push(day)
            }
            this.days = days
        },
        // 根据快速选择的值返回对应的开始结束日期
        getFormatDate(fastDate) {
            var start = new Date(), end = new Date(), now = new Date();
            if(fastDate == '01') {
                end.setTime(start.getTime() - 3600 * 1000 * 24);
                start.setTime(start.getTime() - 3600 * 1000 * 24);
            }
            if(fastDate == '02') {
                start = new Date(now.getFullYear(),now.getMonth(),now.getDate() - now.getDay() + 1);
            }
            if(fastDate == '03') {
                start.setTime(now.getTime() - (now.getDay()+6)*3600 * 1000 * 24);
                end.setTime(now.getTime() - (now.getDay()+0)*3600 * 1000 * 24);
            }
            if(fastDate == '04') {
                start = new Date(now.getFullYear(), now.getMonth(), 1);
            }
            if(fastDate == '05') {
                var year = now.getFullYear();
                var month = now.getMonth();
                if (month == 0) {
                    month = 12;
                    year = year - 1;
                }
                var lastDay = new Date(year, month, 0);
                start = new Date(year + "-" + month + "-" + 1);
                end = new Date(year + "-" + month + "-" + lastDay.getDate());
            }
            if(fastDate == '06') {
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            }
            if(fastDate == '07') {
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            }
            if(fastDate == '08') {
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            }
            if(fastDate == '09') {
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
            }
            return [start.format('yyyy-MM-dd'), end.format('yyyy-MM-dd')]
        },
        // 设置默认选中的快捷日期
        setDefaultActFast() {
            for(let i = 0; i<this.showFastList.length; i++) {
                let item = this.showFastList[i]
                let timeArr = this.getFormatDate(item.value)
                if(timeArr.join('') == this.searchTime.join('')) {
                    this.actFast = item.value
                    break;
                }
            }

        }

    }

}
</script>

<style lang="less" scoped>
.fast_date_picker{
    position: relative;
    .mask{
        width: 100%;
        height: 100%;
        position: fixed;
        z-index: 1;
        background: rgba(0,0,0,0.5);
    }
    .btns{
        background: #fff;
        position: relative;
        z-index: 10;
    }
    .picker{
        width: 100%;
        background: #fff;
        position: absolute;
        z-index: 10;
        padding-bottom: 20rpx;

        .date_range{
            padding: 20rpx 30rpx;
            font-size: 28rpx;
            >div{
                width: 280rpx;
                height: 60rpx;
                line-height: 60rpx;
                border-radius: 30rpx;
                background: #eee;
                text-align: center;
                border: 1px solid #fff;
            }
        }
        .picker_view{
            width: 100%;
            height: 300rpx;
            .item{
                text-align: center;
            }
        }
        .confirm_btn{
            width: 620rpx;
            height: 60rpx;
            line-height: 60rpx;
            color: #fff;
            border-radius: 10rpx;
            text-align: center;
            margin: 40rpx auto 0;
            background: @mainColor;
        }
    }
}
.btns{
    display: flex;
    width: 100%;
    padding: 20rpx 30rpx;
    overflow: auto;
    border-bottom: 1rpx solid #eee;
    &::-webkit-scrollbar {
        display: none;
        width: 0;
        height: 0;
        color: transparent;
    }
    .btn{
        height: 44rpx;
        line-height: 44rpx;
        padding: 0 20rpx;
        margin-right: 10rpx;
        flex-shrink: 0;
        font-size: 26rpx;
        border-radius: 25rpx;
        border: 1rpx solid #999;
        color: #999;
        &.active{
            color: #fff;
            border: 0;
            background: @mainColor;
        }
    }
}

</style>
